package com.link.gateway.core.redis.redisclient;

import com.link.gateway.core.utils.YmlConstants;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * @auther LiYang
 * @date 20190417
 *
 * JedisCluster配置类
 */
public class JedisClusterSingleton {

    private static final Logger logger = LogManager.getLogger(JedisClusterSingleton.class);

    private static volatile JedisClusterSingleton instance;

    private JedisCluster jedisCluster;

    public static JedisClusterSingleton getInstance() {
        if (null == instance) {
            synchronized (JedisClusterSingleton.class) {
                if (null == instance) {
                    instance = new JedisClusterSingleton();
                }
            }
        }
        return instance;
    }

    /**
     * @auther LiYang
     * @date 20190417
     *
     * 初始化一个JedisCluster对象
     * @return
     */
    public JedisClusterSingleton() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(YmlConstants.getRedisPoolMaxIdle());
        poolConfig.setMaxTotal(YmlConstants.getRedisPoolMaxTotal());
        poolConfig.setMinIdle(YmlConstants.getRedisPoolMinIdle());
        poolConfig.setMaxWaitMillis(YmlConstants.getRedisPoolMaxWait());
        //读取配置文件中的配置
        String redisClusterNodes = YmlConstants.getRedisClusterNodes();
        Integer redisClusterCommandTimeout = YmlConstants.getRedisClusterCommandTimeout();
        String redisClusterPassword = YmlConstants.getRedisClusterPassword();
        //获取服务器数组
        logger.error("获取到的redis#cluster节点：" + redisClusterNodes);
        String[] serverArray = redisClusterNodes.split(",");
        Set<HostAndPort> nodes = new HashSet<>();

        for (String ipPort : serverArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }
        JedisCluster jedisCluster = new JedisCluster(nodes, redisClusterCommandTimeout, 10000, 3,
                redisClusterPassword, poolConfig);
        this.jedisCluster = jedisCluster;
    }

    public JedisCluster getJedisCluster() {
        return jedisCluster;
    }
}
